﻿#include "uilogindialog.h"
#include "src/middle/managers/mandb.h"
#include "src/middle/config/common.h"
#include "ui_uilogindialog.h"

#include <QMessageBox>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QCompleter>
#include <QJsonObject>

UiLoginDialog::UiLoginDialog(QWidget *parent)
    : UiQosDialog(parent), ui(new Ui::UiLoginDialog)
{
    // 注: 要将登录界面的 UI 初始化到 widgetBody 上,
    // 而不是 ui->setupUi(this);
    ui->setupUi(body());

    setTitle(STR("OS Viewer"));

    // 登录按钮设置
    ui->btnLogin->setDefault(true);
    ui->btnLogin->setProperty("style_font", "h5");
    ui->btnLogin->setProperty("style_button", "main");

    // 其他标签设置
    ui->labelLoginName->setProperty("style_font", "h5");
    ui->labelSecretId->setProperty("style_font", "h5");
    ui->labelSecretKey->setProperty("style_font", "h5");
    ui->labelRemark->setProperty("style_font", "h5");

    // 信号设置
    connect(ui->btnLogin, &QPushButton::clicked, this,
            &UiLoginDialog::onBtnLoginClicked);

    connect(MG->mSignal, &ManSignals::loginSuccess, this,
            &UiLoginDialog::onLoginSucceed);
    connect(MG->mSignal, &ManSignals::error, this,
            &UiLoginDialog::onLoginError);
    connect(MG->mSignal, &ManSignals::unLogin, this, &UiLoginDialog::show);

    connect(ui->lineLoginName, &UiComboLine::itemSelected,
            [=](const QString &name) {
                LoginInfo info = MG->mDb->loginInfoByName(name);
                ui->lineSecretId->setText(info.secret_id);
                ui->lineSecretKey->setText(info.secret_key);
                ui->lineRemark->setText(info.remark);
                ui->checkSaveSection->setChecked(true);
            });

    // 设置会话输入框的视图(快捷会话列表选择)
    QStringList words = MG->mDb->loginNameList();
    ui->lineLoginName->setWords(words);

    // 设置界面大小
    resize(400, 450);
}

UiLoginDialog::~UiLoginDialog()
{
    delete ui;
}

bool UiLoginDialog::eventFilter(QObject *watched, QEvent *event)
{
    // 禁止密钥输入框的复制/粘贴行为
    // 即使用事件过滤器, 拦截键盘的 Ctrl + C/V 事件

    bool intercepted = [&]() {
        if (watched != ui->lineSecretKey ||
            event->type() != QEvent::KeyPress) {
            return false;
        }

        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        if (keyEvent->modifiers() != Qt::ControlModifier) {
            return false;
        }
        if (keyEvent->key() != Qt::Key_C && keyEvent->key() != Qt::Key_V) {
            return false;
        }
        return true;
    }();

    if (intercepted) {
        return true; // true: 事件已经被处理，不再往下传递, false: 继续执行传递
    } else {
        return QDialog::eventFilter(watched, event);
    }
}

void UiLoginDialog::onBtnLoginClicked()
{
    QJsonObject params;
    params["secretId"] = ui->lineSecretId->text().trimmed();
    params["secretKey"] = ui->lineSecretKey->text().trimmed();

    // 将登录请求通过网关发送给后端
    MG->mGate->send(API::LOGIN::NORMAL, params);
}

void UiLoginDialog::onLoginSucceed()
{
    if (ui->checkSaveSection->isChecked()) {
        MG->mDb->saveLoginInfo(
                ui->lineLoginName->text(), ui->lineSecretId->text(),
                ui->lineSecretKey->text(), ui->lineRemark->text());
    } else {
        MG->mDb->removeLoginInfo(ui->lineSecretId->text());
    }
    accept();
}

void UiLoginDialog::onLoginError(
        int api,
        const QString &msg,
        const QJsonValue &req)
{
    Q_UNUSED(req)

    if (api != API::LOGIN::NORMAL) {
        return;
    }
    QMessageBox::warning(this, STR("登录失败"), STR("登录失败：%1").arg(msg));
}
